package com.uking.moudle;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TableLayout;

import com.smalls.newvideotwo.BuildConfig;
import com.smalls.newvideotwo.media.InfoHudViewHolder;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.uking.udppush.UdpHelper;
import com.uking.ukingmodule.ukingjnic.onStateChangeLisenser;
import com.uking.util.VKConstant;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import static com.uking.util.Constants.DEFAULT_LIVE_PORT;
import static com.uking.util.VKConstant.DEFAULT_VOD_PORT;

public class UKingPlayerIJKImpl implements  SurfaceHolder.Callback{

	/**
	 * 播放器在准备中
	 */
	public static final int PLAYER_PREPARING = 0xf100;

	/**
	 * 播放器准备好了
	 */
	public static final int PLAYER_PREPARED = 0xf101;

	/**
	 * 播放器缓冲开始
	 */
	public static final int PLAYER_BUFFERING_START = 0xf102;

	/**
	 * 播放器缓冲结束
	 */
	public static final int PLAYER_BUFFERING_END = 0xf103;

	/**
	 * 播放器错误
	 */
	public static final int PLAYER_ERROR = 0xf104;

	/**
	 * 播放器seek结束
	 */
	public static final int PLAYER_SEEK_END = 0xf105;

	/**
	 * 播放器进度信息
	 */
	public static final int PLAYER_PROGRESS_INFO = 0xf106;

	/**
	 * 播放节目完 了
	 */
	public static final int PLAYER_COMPLETE = 0xf107;

	public static final int PLAYER_STATUS_PLAYING = 1;
	public static final int PLAYER_STATUS_STOPED = 2;
	public static final int PLAYER_STATUS_PAUSE = 3;

	/**
	 * 播放器不能seek的信息
	 */
	public static final int PLAYER_CAN_NOT_SEEK = 0xf108;

	private int  errorFlag=0x00;

	private static final String TAG = "VKPlayer";
	private int videoWidth;
	private int videoHeight;
	private IjkMediaPlayer mMediaPlayer;
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;

	private int StartdownLoadResult = 1;

	// 初始化Player的时候传递进来的Handler，向播放activity发送播放器状态信息
	private Handler mNotifyHandler;

	private Handler knJniHander;
	private String mMediaCode=null;
	/**
	 * 127.0.0.1:9999 这种形式的本地流地址
	 */
	private String mPlayUrl = null;

	private String mLastPlayUrl = null;
	private SeekBar mSukingProgress;

	private long mLastBufferingTime = 0;
	private long mChannelStartTime = 0;
	private int mBufferingCount = 0;


	private long mPrepareStartTime = 0;
	private long mPrepareEndTime = 0;

	private long mSeekStartTime = 0;
	private long mSeekEndTime = 0;

	/**
	 * 是否是直播
	 */
	private boolean mIsLive = false;
	private int mBufferDelayMS = 4000;

	/**
	 * 播放器中间件模块接口实现的实例
	 */
	private PlayerJniInterface ukingjni ;
	private Context mContext ;
	private VKPlayerRatio playerRatio;
	private InfoHudViewHolder mHudViewHolder;
	private int mPlayerStatus = -1;

	/**
	 * 是否是三代盒子
	 */
	private boolean isHtv3 = true;
	/**
	 * 播放器屏幕比例
	 */
	public enum VKPlayerRatio {
	  VKPlayer_4_3,
	  VKPlayer_16_9,
	  VKPlayer_ORIGINAL,
	  VKPlayer_DEFAULT,
	};


	/**
	 * 播放器构造函数
	 *
	 * @param context
	 * @param surfaceView
	 * @param handler
	 *            此handler属于activity的，来获取播放器的消息
	 * @param sukingProgress
	 *            进度条
	 * @param isLive
	 *            直播点播类型
	 */
	@SuppressWarnings("deprecation")
	public UKingPlayerIJKImpl(Context context, SurfaceView surfaceView, Handler handler,
			SeekBar sukingProgress,Handler JniHander,boolean isLive) {
		mContext = context ;
		mNotifyHandler = handler;
		knJniHander = JniHander;
		mSukingProgress = sukingProgress;
		mSurfaceView = surfaceView;
		mIsLive = isLive;

		LogUtil.e(TAG,"设置好了播放类型 ======================== mIsLive = "+mIsLive);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		ukingjni = new PlayerJniImple(monStateChangeLisenser) ;

		/**
		 * 注册中间件UDP消息的接收
		 */
		IntentFilter filter = new IntentFilter(UdpHelper.ACTION_RECEIVE_UDP_MSG) ;
		context.registerReceiver(middlewareMsgReciever, filter) ;

		/**
		 * 初始化播放器中间件模块
		 */
		ukingjni.onInit(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD,
				mIsLive ? VKConstant.DEFAULT_LIVE_PORT : DEFAULT_VOD_PORT) ;

	}

	/**
	 *
	 * @param surfaceView
	 */
	@SuppressWarnings("deprecation")
	public void open(SurfaceView surfaceView) {
		LogUtil.d(TAG, "open()......");
		mSurfaceView = surfaceView;
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	boolean isUnRegisterReceiver = false ;
	public void close() {
		////stopTimer();
		LogUtil.d(TAG, "mediaplayer has close()......");
		if(mNotifyHandler!=null){
			mNotifyHandler.removeCallbacks(mRunable);
			LogUtil.d(TAG, "mNotifyHandler.removeCallbacks(mRunable);");
			releaseMediaPlayer();
			if(!isUnRegisterReceiver){
				mContext.unregisterReceiver(middlewareMsgReciever) ;
				isUnRegisterReceiver = true ;
			}
		}
		mMediaCode= null;
	}
	static private void SetMediaPlayerOptions(IjkMediaPlayer ijkMediaPlayer,boolean enabledebug)
	{
			if(ijkMediaPlayer==null) {
				return;
			}

		//打开h265硬解
		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-hevc", 1);
		if(BuildConfig.isDebug)
			ijkMediaPlayer.native_setLogLevel(IjkMediaPlayer.IJK_LOG_INFO);
		else
			ijkMediaPlayer.native_setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT);

		ijkMediaPlayer.setOption(4, "framedrop", 1L);
		//播放前的探测Size，默认是1M, 改小一点会出画面更快
//		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 1024 * 100L);

//		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "next-high-water-mark-ms",500L);
////		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "last-high-water-mark-ms",2500L);
		//设置播放前的探测时间 1,达到首屏秒开效果
		//ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT,"analyzeduration",5);

		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", 100 * 1024);//设置缓冲区为100KB，目前我看来，多缓冲了4秒
//		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-sync", 1);

//		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", 25);// 视频的话，设置100帧即开始播放

		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", 1);//重连模式，如果中途服务器断开了连接，让它重新连接
		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", 1);
		//ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
		if (true) {
			ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
			if (false) {
				ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1);
			} else {
				ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 0);
			}
			if (false) {
				ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 1);
			} else {
				ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 0);
			}
		} else {
			ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 0);
		}

		if (false) {
			ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 1);
		} else {
			ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 0);
		}

//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 1);
//		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", IjkMediaPlayer.SDL_FCC_RV32);

		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1);
		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);

		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", 0);

		ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 0);


	}
	private void createMediaPlayer() {

		LogUtil.d(TAG, "createMediaPlayer()......");
		// init player
		IjkMediaPlayer.loadLibrariesOnce(null);
		IjkMediaPlayer.native_profileBegin("libijkplayer.so");

		try {
			if (mMediaPlayer != null) {
				mMediaPlayer.release();
				mMediaPlayer = null;
			}
			mMediaPlayer = new IjkMediaPlayer();
			{
				SetMediaPlayerOptions(mMediaPlayer,true);
			}

			mMediaPlayer.setOnPreparedListener(mPreparedListener);
			mMediaPlayer.setOnErrorListener(mErrorListener);
			mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
			mMediaPlayer.setOnInfoListener(mInfoListener);
			mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
			mMediaPlayer.setOnCompletionListener(mCompletionListener);

			//setPlayRatio(mIsLive); //设置播放比例
			mMediaPlayer.setDisplay(mSurfaceHolder);
			mMediaPlayer.setScreenOnWhilePlaying(true);
//			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//			AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
//			am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	/**
	 * 设置播放比例
	 *
	 */
	private void setPlayRatio(int mVideoWidth,int mVideoHeight, boolean isLive){
		 if(isLive || playerRatio == null) {
			 return ;
		 }
		 int width;
		 int height;
		 WindowManager mWm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
		 Integer screenWidth = mWm.getDefaultDisplay().getWidth();
		 Integer screenHeight = mWm.getDefaultDisplay().getHeight();
		 android.view.ViewGroup.LayoutParams videoParams = mSurfaceView.getLayoutParams();
		 //原始比例和默认比例
		 if(playerRatio.equals(VKPlayerRatio.VKPlayer_DEFAULT)
				 || playerRatio.equals(VKPlayerRatio.VKPlayer_ORIGINAL)){
			 if (mVideoWidth != 0 && mVideoHeight != 0) {
				 ViewGroup.LayoutParams layoutParams = mSurfaceView.getLayoutParams();

				 // 如果video的宽或者高超出了当前屏幕的大小，则要进行缩放
				 float wRatio = (float) mVideoWidth / (float) screenWidth;
				 float hRatio = (float) mVideoHeight / (float) screenHeight;

				 // 选择大的一个进行缩放
				 float ratio = Math.max(wRatio, hRatio);
				 mVideoWidth = (int) Math.ceil((float) mVideoWidth / ratio);
				 mVideoHeight = (int) Math.ceil((float) mVideoHeight / ratio);

				 layoutParams.width = mVideoWidth;
				 layoutParams.height = mVideoHeight;
				 mSurfaceView.setLayoutParams(layoutParams);
				 mSurfaceView.getHolder().setFixedSize(layoutParams.width, layoutParams.height);
			 }
		 }else if(playerRatio.equals(VKPlayerRatio.VKPlayer_4_3) ){  //4:3
			 if (mVideoWidth != 0 && mVideoHeight != 0) {
				 ViewGroup.LayoutParams layoutParams = mSurfaceView.getLayoutParams();
				 width = mSurfaceView.getWidth();
				 height = mSurfaceView.getHeight();
				 if (width * 3 / 4 >= height) {
					 layoutParams.width = height * 4 / 3;
					 layoutParams.height = height;
				 } else {
					 layoutParams.width = width;
					 layoutParams.height = width * 3 / 4;
				 }
				 mSurfaceView.setLayoutParams(layoutParams);
				 mSurfaceView.getHolder().setFixedSize(layoutParams.width, layoutParams.height);
			 }
		 }else if(playerRatio.equals(VKPlayerRatio.VKPlayer_16_9) ){  //16:9
			 if (mVideoWidth != 0 && mVideoHeight != 0) {
				 ViewGroup.LayoutParams layoutParams = mSurfaceView.getLayoutParams();
				 width = mSurfaceView.getWidth();
				 height = mSurfaceView.getHeight();
				 if (width * 9 / 16 >= height) {
					 layoutParams.width = height * 16 / 9;
					 layoutParams.height = height;
				 } else {
					 layoutParams.width = width;
					 layoutParams.height = width * 9 / 16;
				 }
				 mSurfaceView.setLayoutParams(layoutParams);
				 mSurfaceView.getHolder().setFixedSize(layoutParams.width, layoutParams.height);
			 }
		 }
		 mSurfaceView.invalidate();

	}
	public void setHudView(TableLayout tableLayout) {
		mHudViewHolder = new InfoHudViewHolder(mContext, tableLayout);
	}
	/**
	 * 上层调用
	 * 设置播放比例
	 * @param ratio
	 */
	public void setMediaPlayerRatio(VKPlayerRatio ratio) {

		playerRatio = ratio;
	}

	/**
	 * 上层调用
	 *
	 * @param videoUrl
	 */
	public void playUrl(String videoUrl) {
		//stopTimer();
		LogUtil.d(TAG, "playUrl..."+videoUrl);
		open(mSurfaceView); // 初始化surfaceView

		if(mIsLive) {
			mPlayUrl = Constant.LOC_PLAYER_ADDR + DEFAULT_LIVE_PORT + "/" + videoUrl;
		} else {
			mPlayUrl = Constant.LOC_PLAYER_ADDR + DEFAULT_VOD_PORT + "/" + videoUrl;
		}

		if(mLastPlayUrl!= null && !mLastPlayUrl.trim().equals(videoUrl)){
			count = 0;
			mBufferingCount = 0;
			mLastBufferingTime = 0;
		}

		startJniDownload(videoUrl);
		if(VKConstant.B_ENABLE_HLS_MODE) {
			LogUtil.d(TAG, "HLS方式播放,先不设置播放器的播放地址");
		}else
		{
			mLastPlayUrl = videoUrl;
			openVideo();
		}


		stopNotify(); // 移除上次播放的info事件
	}

	public void replay() {// vod no this method
		//stopTimer();
		LogUtil.d(TAG, "replay()......" + " ,mLastPlayUrl is:" + mLastPlayUrl);
		if (mLastPlayUrl != null) {
			playUrl(mLastPlayUrl);
		}

	}

	public void stop() {
		//stopTimer();
		LogUtil.d(TAG, "stop()......");
		if(!VKConstant.B_ENABLE_HLS_MODE)
			ukingjni.onDestroy(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD);
		if (mMediaPlayer != null&&mPlayerStatus!=PLAYER_STATUS_STOPED) {
			if (mIsLive) {
				mLastPlayUrl = null;
			}
			if (mHudViewHolder != null)
				mHudViewHolder.setMediaPlayer(null);
			mMediaPlayer.stop();
			mPlayerStatus = PLAYER_STATUS_STOPED;
		}
	}

	public void pause() {
		//stopTimer();
		LogUtil.d(TAG, "pause()......");
		if (mMediaPlayer != null) {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.pause();
				mPlayerStatus = PLAYER_STATUS_PAUSE;
			}
		}
	}

	public void resume() {
		//stopTimer();
		LogUtil.d(TAG, "resume()......");
		if (mMediaPlayer != null) {
			if (!mMediaPlayer.isPlaying()) {
				mMediaPlayer.start();
				mPlayerStatus = PLAYER_STATUS_PLAYING;
			}
		}
	}

	public void start() {
		if(StartdownLoadResult>=0&&mMediaCode!=null) {
			StartdownLoadResult = ukingjni.onDoWork(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD, mMediaCode);
		}
	}

	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		LogUtil.d(TAG, "surfaceChanged()......");
		mSurfaceHolder = arg0;
	}

	public void surfaceCreated(SurfaceHolder arg0) {
		mSurfaceHolder = arg0;
		LogUtil.d(TAG, "surfaceCreated()......"+mSurfaceHolder);
		createMediaPlayer();
		openVideo();
	}

	public void surfaceDestroyed(SurfaceHolder arg0) {
		LogUtil.d(TAG, "surfaceDestroyed()......");
		stop();
		close();
	}

	private void openVideo() {

		LogUtil.d(TAG, "openVideo()......mPlayUrl="+mPlayUrl);
			if (mPlayUrl == null || mSurfaceHolder == null) {
				LogUtil.d(TAG, "mPlayUrl or mSurfaceHolder is null");
				return;
			}
			synchronized (this) {
				try {
					if (mMediaPlayer != null) {
						mMediaPlayer.reset();
						mMediaPlayer.setDataSource(mPlayUrl);
						SetMediaPlayerOptions(mMediaPlayer,true);
						mMediaPlayer.setDisplay(mSurfaceHolder);
						mPrepareStartTime = System.currentTimeMillis();
						mMediaPlayer.prepareAsync();
						if (mHudViewHolder != null)
							mHudViewHolder.setMediaPlayer(mMediaPlayer);
						mPlayerStatus = PLAYER_STATUS_PLAYING;
//						startNotify(); //没有播放出来。不需上传info事件，而且会造成多次执行
					} else {
						LogUtil.d(TAG, "mMediaPlayer is null");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

	}

	private void releaseMediaPlayer() {
		LogUtil.d(TAG, "mediaplayer has releaseMediaPlayer()......mPlayerStatus="+mPlayerStatus);
		synchronized (this) {
			if (mMediaPlayer != null&&mPlayerStatus!=PLAYER_STATUS_STOPED) {
				LogUtil.d(TAG, "mediaplayer has stop()......");
				mMediaPlayer.stop();
				mPlayerStatus = PLAYER_STATUS_STOPED;
			}
			if (mMediaPlayer != null) {
				LogUtil.d(TAG, "mediaplayer has release()......mPlayerStatus="+mPlayerStatus);
				mMediaPlayer.release();
				ukingjni.onDestroy(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD);
			}
			mMediaPlayer = null;
		}

	}



	private IMediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener =
			new IMediaPlayer.OnBufferingUpdateListener() {
				public void onBufferingUpdate(IMediaPlayer mp, int percent) {
					//LogUtil.d(TAG, "onBufferingUpdate: " + bufferingProgress + "% buffer");
					//		 LogUtil.e(TAG, "% play, " + bufferingProgress
					//				 + "% buffer");
					//		 if(mLastBufferingTime > 0 ){
										resumeFromBuffer();
					//		 }
				}
			};

	private IMediaPlayer.OnCompletionListener mCompletionListener =
			new IMediaPlayer.OnCompletionListener() {
				public void onCompletion(IMediaPlayer mp) {
					LogUtil.d(TAG, "onCompletion()......");


					if (mNotifyHandler != null) {
						LogUtil.d(TAG,"点播播放结束");
						if(errorFlag!=-38&&errorFlag!=1){
							mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_COMPLETE);
							LogUtil.e(TAG, "Flag="+errorFlag);
						}else{
							errorFlag=0x00;
						}
					}
				}
			};



	IMediaPlayer.OnPreparedListener mPreparedListener = new IMediaPlayer.OnPreparedListener() {
		public void onPrepared(IMediaPlayer mp) {

			//stopTimer();
			startNotify();
			LogUtil.d(TAG, "onPrepared()......");
			if (mMediaPlayer != null) {
				mPrepareEndTime = System.currentTimeMillis();
				if(mHudViewHolder!=null) {
					mHudViewHolder.updateLoadCost(mPrepareEndTime - mPrepareStartTime);
				}
				videoWidth = mMediaPlayer.getVideoWidth();
				videoHeight = mMediaPlayer.getVideoHeight();
				setPlayRatio(videoWidth,videoHeight,mIsLive); //设置播放比例
				LogUtil.d(TAG, "videoWidth=" + videoWidth);
				LogUtil.d(TAG, "videoHeight=" + videoHeight);
				if (mIsLive) {
					if (mNotifyHandler != null) {
						mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_PREPARED);
					}
					mp.start();
				} else {
					if (mNotifyHandler != null) {
						mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_PREPARED);
					}
					mp.start();
				}
			} else {
				LogUtil.d(TAG, "mMediaPlayer = null");
			}
		}
	};
	int count=0;
	private IMediaPlayer.OnErrorListener mErrorListener =
			new IMediaPlayer.OnErrorListener() {
				public boolean onError(IMediaPlayer mp, int what, int extra) {
					count++;
					// TODO Auto-generated method stub
					LogUtil.d(TAG, "onError()......what= " + what + " extra=" + extra);
					if (mNotifyHandler != null && StartdownLoadResult > 0) {
						Message msg = mNotifyHandler.obtainMessage(UKingPlayerIJKImpl.PLAYER_ERROR,
								what, extra);
						errorFlag=what;
						mNotifyHandler.sendMessage(msg);
					}
					if(!mIsLive && count > 5) {
						close();
					}
					return false;
				};

			};

	long startBufTime = 0;
	long endBufTime = 0;

	private IMediaPlayer.OnInfoListener mInfoListener =
			new IMediaPlayer.OnInfoListener() {
				public boolean onInfo(IMediaPlayer mp, int what, int extra) {
					// TODO Auto-generated method stub
					LogUtil.d(TAG, "onInfo()......what = " + what + " extra = " + extra);
					switch (what) {
						case IjkMediaPlayer.MEDIA_INFO_BUFFERING_START:
							//优化缓冲时UI显示方式
							startBufTime = System.currentTimeMillis();

							if (mMediaPlayer != null) {
								if (mNotifyHandler != null) {
									mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_BUFFERING_START);
								}
							}

							break;
						case IjkMediaPlayer.MEDIA_INFO_BUFFERING_END:
							endBufTime = System.currentTimeMillis();
							mLastBufferingTime += (endBufTime - startBufTime);

							if (mMediaPlayer != null) {
								if (mNotifyHandler != null) {
									mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_BUFFERING_END);
								}
							}

							break;
						case IjkMediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
							LogUtil.d(TAG, "BAD_INTERLEAVING...");
							break;
						case IjkMediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
							LogUtil.d(TAG, "NOT_SEEKABLE...");
							if (mNotifyHandler != null) {
								mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_CAN_NOT_SEEK);
							}
							break;
						case IjkMediaPlayer.MEDIA_INFO_UNKNOWN:
							LogUtil.d(TAG, "UNKNOWN...");
							break;
					}
					return false;
				}
			};

	private IMediaPlayer.OnSeekCompleteListener mSeekCompleteListener = new IMediaPlayer.OnSeekCompleteListener() {

		@Override
		public void onSeekComplete(IMediaPlayer mp) {
			// TODO Auto-generated method stub
			LogUtil.d(TAG, "onSeekComplete()......");
			if (mNotifyHandler != null) {
				mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_SEEK_END);
			}
			mSeekEndTime = System.currentTimeMillis();
			if(mHudViewHolder!=null) {
				mHudViewHolder.updateSeekCost(mSeekEndTime - mSeekStartTime);
			}
		}
	};




	/**
	 * 开始下载并推流
	 * @param url 节目url
	 * @return
	 */
	private int startJniDownload(String url) {
		LogUtil.d(TAG, "startJniDownload(String url)" + url);
		String mediaCode = url;
		LogUtil.d(TAG, "mediaCode = " + mediaCode+",mIsLive:"+mIsLive);
		/**
		 * 开始下载并推流
		 */
		StartdownLoadResult = ukingjni.onDoWork(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD, mediaCode);
		LogUtil.d(TAG, "StartdownLoadResult  -----> "+StartdownLoadResult);
		if(StartdownLoadResult < 0){
			StartdownLoadResult=ukingjni.initDownloadModul(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD,
					mIsLive ? VKConstant.DEFAULT_LIVE_PORT : DEFAULT_VOD_PORT);
			if(StartdownLoadResult<0) {
				StartdownLoadResult=ukingjni.initDownloadModul(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD,
						mIsLive ? VKConstant.DEFAULT_LIVE_PORT : DEFAULT_VOD_PORT);
			}
			StartdownLoadResult = ukingjni.onDoWork(mIsLive ? VKConstant.TYPE_LIVE : VKConstant.TYPE_VOD, mediaCode);
			mMediaCode = mediaCode;
		}

		if(StartdownLoadResult < 0 ) {
			Message message = knJniHander.obtainMessage(ukingplayer_info.ukingMSG_LIBEXIT) ;
			knJniHander.sendMessage(message);
		}
		return StartdownLoadResult;
	}

	public IjkMediaPlayer getMediaPlayer() {
		// LogUtil.d(TAG, "getMediaPlayer()......");
		return mMediaPlayer;
	}

	public void startNotify() {
		LogUtil.d(TAG, "startNotify()......");
		if (mNotifyHandler != null) {
			mNotifyHandler.post(mRunable);
		}
	}

	public void stopNotify(){
		LogUtil.d(TAG, "stopNotify()......");
		if(mNotifyHandler!=null) {
			mNotifyHandler.removeCallbacks(mRunable);
		}
	}

	/**
	 * 每隔1000 毫秒发送一次播放器的 进度条 更新信息
	 */
	long mSeekLastTime = System.currentTimeMillis();
	Runnable mRunable = new Runnable() {

		public void run() {
			if (mNotifyHandler != null) {
				if(System.currentTimeMillis() - mSeekLastTime >= 1000) {
					mSeekLastTime = System.currentTimeMillis();
					Message msg = new Message();
					msg.what = PLAYER_PROGRESS_INFO;
					mNotifyHandler.sendMessage(msg);
				}
				mNotifyHandler.postDelayed(mRunable, 1000);
			}
		}
	};

	private Runnable mPrepare = new Runnable (){

		@Override
		public void run() {
			if(mMediaPlayer!=null&&!mMediaPlayer.isPlaying()) {
				mMediaPlayer.start();
			}
			if (mNotifyHandler != null) {
				mNotifyHandler.sendEmptyMessage(UKingPlayerIJKImpl.PLAYER_PREPARED);
			}
		}
	};

	public void seekTo(long msec) {
		LogUtil.i(TAG, "seekTo"+msec);
		if (mMediaPlayer != null) {
			mSeekStartTime = System.currentTimeMillis();
			mMediaPlayer.seekTo(msec);
		}

	}

	/**
	 *
	 * 类说明：内部类，用于接受中间件向Player发送的消息 ，消息采用UDP协议
	 */
	BroadcastReceiver middlewareMsgReciever = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			if(intent.getAction().equals(UdpHelper.ACTION_RECEIVE_UDP_MSG)){
				String receiver_msg = intent.getStringExtra("udp_message") ;
				LogUtil.d(TAG, "播放器中间件发送过来的消息 ：receiver_msg = "+receiver_msg) ;
				String temp = receiver_msg.substring(receiver_msg.indexOf("CODE=")+5,receiver_msg.indexOf("&INFO")).trim() ;
				LogUtil.d(TAG, "播放器中间件发送过来的消息 ：type = "+temp);
				int type = 0;
				try {
					type = Integer.parseInt(temp);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(type != 0){
					Message message = knJniHander.obtainMessage(type) ;
					knJniHander.sendMessage(message);
				}

			}
		}

	} ;

	private onStateChangeLisenser monStateChangeLisenser = new onStateChangeLisenser() {
		public void StateChanged(int msg, String msgContent) {
			LogUtil.i(TAG, "############################得到中间件消息$$$$$$$$$$$$$$$$$$$$$$$$$$" + msg + "msgContent:" +msgContent);
			if(msg==1)
			{
				int codeIndex = msgContent.indexOf("CODE=");
				int urlIndex = msgContent.indexOf("INFO=");
				if(codeIndex!=-1&&urlIndex!=-1)
				{
					String media_code=msgContent.substring(codeIndex+5,urlIndex);
					String play_url=msgContent.substring(urlIndex+5);
					LogUtil.i(TAG, "############################media_code:"+media_code+"play_url:"+play_url+"$$$$$$$$$$$$$$$$$$$$$$$$$$" + msg + "msgContent:" +msgContent);
					mPlayUrl=play_url;
					openVideo();
				}else {
					LogUtil.i(TAG, "############################得到中间件消息,但是协议错误$$$$$$$$$$$$$$$$$$$$$$$$$$" + msg + "msgContent:" +msgContent);
				}

			}
		}
	};


	private void resumeFromBuffer(){
//		endBufTime = System.currentTimeMillis();
//
//		mLastBufferingTime += (endBufTime - startBufTime);
////		LogUtil.d(TAG, "Time..." + mLastBufferingTime);
//		if(mLastBufferingTime > 100){
//			if (mNotifyHandler != null) {
//				mNotifyHandler.sendEmptyMessage(VKPlayer.PLAYER_BUFFERING_END);
//			}
////			if (!mIsLive) {
////				if (mMediaPlayer != null && mMediaPlayer.isPlaying() == false) {
//////					LogUtil.d(TAG, "resume from buffering...");
////					mMediaPlayer.start();
////				}
////			}
//			mLastBufferingTime = 0;
//		}
	}
//
//
//	//优化缓冲时UI显示方式
//	class MyTimerTask extends TimerTask {
//
//		@Override
//		public void run() {
//			// TODO Auto-generated method stub
//			LogUtil.d(TAG, "*********** timer will buffer the program***********");
//			if (mNotifyHandler != null) {
//				if(mMediaPlayer != null){
//					if(mMediaPlayer.isPlaying()==true){
//						mNotifyHandler.sendEmptyMessage(VKPlayer.PLAYER_BUFFERING_END);
//						//stopTimer();
//					}else{
//						startTimer();
//					}
//				}
//			}
//		}
//
//	}
//
//	private void startTimer() {
//		LogUtil.d(TAG, "startTimer()......");
//		if (mTimer == null) {
//			mTimer = new Timer();
//		}
//
//		if (mTimerTask == null) {
//			mTimerTask = new MyTimerTask();
//		}
//
//		if (mTimer != null && mTimerTask != null
//				&& isTimerRun == false) {
//			mTimer.schedule(mTimerTask, 2000);
//			isTimerRun = true;
//		}
//
//	}
//
//	private void stopTimer() {
//		LogUtil.d(TAG, "stopTimer()......");
//		if (mTimer != null) {
//			mTimer.cancel();
//			mTimer = null;
//		}
//
//		if (mTimerTask != null) {
//			mTimerTask.cancel();
//			mTimerTask = null;
//		}
//
//		isTimerRun = false;
//	}
//
//
//
//	private Timer mTimer = new Timer();
//	private TimerTask mTimerTask = new MyTimerTask();
//	private boolean isTimerRun;
}
